package com.acegear.horizon.domain.models;

import java.util.Optional;

import com.acegear.horizon.ApplicationContextProvider;
import com.acegear.horizon.domain.events.ActivityCreateEvent;
import com.acegear.horizon.domain.events.processers.EventProcessor;
import com.acegear.horizon.domain.models.jpa.ActivityBase;
import com.acegear.horizon.domain.models.jpa.Address;
import com.acegear.horizon.domain.models.jpa.Location;
import com.acegear.horizon.domain.models.jpa.UserInfo;
import com.acegear.horizon.domain.repository.jpa.ActivityBaseRepository;

public class Activity {
	
	private Long activityId;
	
	private ActivityBase base;
	
	private Address address;
	
	private Location location;
	
	private ActivityBaseRepository activityBaseRepository;

	private EventProcessor eventProcessor;
	
	public Activity(){
		init();
	}
	
	public void init() {
		
		activityBaseRepository = ApplicationContextProvider.getBean(ActivityBaseRepository.class);

		eventProcessor = ApplicationContextProvider.getBean("eventProcessor", EventProcessor.class);

	}
	
	private void publishCreteActivity() {
        eventProcessor.publish(new ActivityCreateEvent(getActivity().getActivityId(), getActivity().getOwnerId(),getActivity().getType(),getActivity().getName(),
        		getActivity().getStartAt(),getActivity().getEndAt(),getActivity().getServicePhone(),getActivity().getCover(),getActivity().getSummary(),getActivity().getMemo(),
        		getActivity().isState(),location,address,getActivity().isDeleted()));
    }
	
	public Activity save(ActivityBase base){
		if(base!=null){
			base = activityBaseRepository.save(base);
		}
		publishCreteActivity();
		return this;
	}
    public ActivityBase getActivity() {
    	if (base == null) {
        	base = activityBaseRepository.findByActivityId(activityId).orElse(new ActivityBase(activityId,null,null,null,null,null,null,false,false));
        }
        return base;
    }
    public Optional<Activity> saveActivity(String name,String servicePhone,String cover,String summary,String memo,boolean state,
    		boolean deleted){
    	Activity activity = new Activity();
    	base = new ActivityBase();
    	base.setName(name);
    	base.setServicePhone(servicePhone);
    	base.setCover(cover);
    	base.setSummary(summary);
    	base.setMemo(memo);
    	base.setDeleted(deleted);
    	//保存
    	activity.save(base);
    	return Optional.of(activity);
    }
	public Long getActivityId() {
		return activityId;
	}

	public void setActivityId(Long activityId) {
		this.activityId = activityId;
	}

	public ActivityBase getBase() {
		return base;
	}

	public void setBase(ActivityBase base) {
		this.base = base;
	}

	public ActivityBaseRepository getActivityBaseRepository() {
		return activityBaseRepository;
	}

	public void setActivityBaseRepository(ActivityBaseRepository activityBaseRepository) {
		this.activityBaseRepository = activityBaseRepository;
	}
	
}
